package com.qf.mxapp.service.Impl;

import com.qf.mxapp.mapper.UserMapper;
import com.qf.mxapp.pojo.User;
import com.qf.mxapp.pojo.dto.UserDto;
import com.qf.mxapp.service.UserService;

import com.qf.mxapp.util.SendSms;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private SendSms sendSms;

    @Autowired
    private RedisTemplate redisTemplate;

    @Resource
    private UserMapper userMapper;

    @Transactional(rollbackFor = Exception.class)

    @Override
    public boolean sendCode(String tel) throws Exception {
        //编写发送短信的业务逻辑
        String code = sendSms.sendCode(tel);
        if (code == null){
            return false;
        }else {
            //将验证码存放在redis数据库里
            ValueOperations vps = redisTemplate.opsForValue();
            vps.set("vcode", code,10L, TimeUnit.MINUTES);
            return true;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public User login(UserDto userDto) {
        ValueOperations vps = redisTemplate.opsForValue();
        String vcode =(String) vps.get("vcode");
        if(vcode != null && userDto.getCode().equals(vcode)){
            User user = userMapper.queryByTel(userDto.getTelephone());
            if(user == null){
                User user1 = new User();
                user1.setTelephone(userDto.getTelephone());
                userMapper.insert(user1);
                return user1;
            }else{
                return user;
            }

        }else{
            return null;
        }
    }
}
